const { db } = require('../db');
const { imgUrl, resultsWithCamelCase } = require('../utils/common');


exports.getUserByOpenId = async (openid) => {
    const sql = "select * from dy_users where openid=?";
    return new Promise((resolve, reject) => {
        db.query(sql, openid, (err, results) => {
            if (err) {
                reject(err);
            } else {
                const result = results[0];
                if (result) {
                    resolve(resultsWithCamelCase(results[0]));
                } else {
                    resolve(null);
                }
            }
        });
    });
}

exports.setUserByOpenId = async (openid, key, value) => {
    const sql = "update dy_users set " + key + "=? where openid=?";
    return new Promise((resolve, reject) => {
        db.query(sql, [value, openid], (err, results) => {
            if (err) {
                reject(err);
            } else {
                resolve(results);
            }
        });
    });
}

exports.insertUserByOpenId = async (openid) => {
    const sql = "insert into dy_users set openid=?, \
    can_use_count=5,all_count=5, avatar=?, nickname=?";
    return new Promise((resolve, reject) => {
        db.query(sql, [openid, imgUrl(), '用户昵称'], (err, results) => {
            if (err) {
                reject(err);
            } else {
                resolve(results.affectedRows == 1);
            }
        });
    });
}

exports.getUserById = async (userId) => {
    const sql = "select * from dy_users where id=?";
    return new Promise((resolve, reject) => {
        db.query(sql, userId, (err, results) => {
            if (err) {
                reject(err);
            } else {
                const result = results[0];
                if (result) {
                    resolve(resultsWithCamelCase(results[0]));
                }
            }
        });
    });
}

exports.getUserByEmail = async (email) => {
    const sql = "select * from dy_users where email=?";
    return new Promise((resolve, reject) => {
        db.query(sql, email, (err, results) => {
            if (err) {
                reject(err);
            } else {
                const result = results[0];
                if (result) {
                    resolve(results[0]);
                }
            }
        });
    });
}

exports.setValueByUserId = async (userId, keyValueObj) => {
    const keyArr = Object.keys(keyValueObj);
    let sqlStr = '';
    for (const key of keyArr) {
        sqlStr += key + '=' + keyValueObj[key] + ',';
    }
    sqlStr = sqlStr.substring(0, sqlStr.length - 1);
    const sql = "update dy_users set " + sqlStr + " where id=?";
    return new Promise((resolve, reject) => {
        db.query(sql, userId, (err, results) => {
            if (err) {
                reject(err);
            } else {
                resolve(results.affectedRows == 1);
            }
        });
    });
}